package org.example;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;


@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
@Fork(1)
@Warmup(iterations = 3)
@Measurement(iterations = 10)
public class JMHMain {

    private static final String STR = "c++/go/cangjie/编程语言 - 文本搜索性能大比拼，谁才是字符串比较的性能王者？请看2024年度性能测试野榜排名——c++/go/cangjie/编程语言";

    private static final String TEXT_RUNE;

    private static final String LAST_ROW_STR;

    private int res;

    static {
        StringBuilder text = new StringBuilder();
        int num = 1000000;
        for (int i = 0; i < num; i++) {
            if (i % 2 == 0) {
                text.append(STR);
            } else {
                text.append("\n").append(STR).append(i).append("\n");
            }
        }
        LAST_ROW_STR = STR + (num + 1);
        text.append(LAST_ROW_STR);
        TEXT_RUNE = text.toString();
    }

    @Benchmark
    public void testKmp() {
        res = findStr(TEXT_RUNE, LAST_ROW_STR);
    }

    @TearDown(Level.Iteration)
    public void showRes() {
        System.out.printf("100万行文本字符串查找目标字符串(KMP算法)，字符串位置：%d\t耗时：", res);
    }

    public int[] getNext(String patternRune) {
        int length = patternRune.length();
        int[] next = new int[length];

        int j;
        String leftStr;
        String rightStr;

        for (int i = 1; i < length; i++) {
            j = 0;
            while (j < i) {
                leftStr = patternRune.substring(0, i - j);
                rightStr = patternRune.substring(j + 1, i + 1);
                if (leftStr.equals(rightStr)) {
                    next[i] = leftStr.length();
                    break;
                }
                j++;
            }
        }
        return next;
    }

    public int findStr(String originRune, String patternRune) {
        int[] next = getNext(patternRune);
        int i = 0;
        int j = 0;
        int hasCommonStrNum;

        while (i < originRune.length()) {
            if (originRune.charAt(i) == patternRune.charAt(j)) {
                j++;
            } else if (j > 0) {
                hasCommonStrNum = next[j - 1];
                j = 0;
                i = i - hasCommonStrNum;
                continue;
            } else {
                j = 0;
            }
            i++;
            if (j == patternRune.length()) {
                return i - patternRune.length();
            }
        }
        return -1;
    }

    public static void main(String[] args) throws Exception {
        Options opt = new OptionsBuilder()
                .include(JMHMain.class.getSimpleName())
                .build();
        new Runner(opt).run();
    }
}